package com.forum.demo.services.impl;

import ch.qos.logback.core.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.forum.demo.common.ResultCode;
import com.forum.demo.mapper.UserMapper;
import com.forum.demo.model.UserInfo;
import com.forum.demo.services.IUserService;
import com.forum.demo.utils.MD5Utils;
import com.forum.demo.utils.UUIDUtils;
import com.forum.demo.utils.checkFailUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Override
    public void createNormalUser(UserInfo user) {
        // 1. 非空检验
        if(user == null || StringUtil.isNullOrEmpty(user.getUsername())
           || StringUtil.isNullOrEmpty(user.getNickname()) || StringUtil.isNullOrEmpty(user.getPassword())) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 2. 判断用户名是否存在
        UserInfo existsUser = userMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getUsername, user.getUsername()));
        if (existsUser != null) {
            checkFailUtils.checkFail("用户名已存在");
        }
        // 3. 生成盐
        String salt = UUIDUtils.UUID_32();
        // 4. 生成密文
        String ciphertext = MD5Utils.md5Salt(user.getPassword(),salt);
        // 6. 写入默认值
        user.setPassword(ciphertext);
        user.setSalt(salt);
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        // 7. 写入数据库
        int row = userMapper.insert(user);
        if (row != 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_CREATE);
        }
        log.info("新用户成功. username = " + user.getUsername() + ". ");
    }

    @Override
    public UserInfo login(String username, String password) {
        // 1. 非空校验
        if (StringUtil.isNullOrEmpty(username) || StringUtil.isNullOrEmpty(password)) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 2. 检查用户是否存在
        UserInfo existsUser = userMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getUsername, username));
        if (existsUser == null || existsUser.getDeleteState() == 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 3.检验密码
        String salt = existsUser.getSalt();
        String ciphertext = MD5Utils.md5Salt(password,salt);
        if (!existsUser.getPassword().equals(ciphertext)) {
            checkFailUtils.checkFail(ResultCode.FAILED_LOGIN);
        }
        log.info("登录成功, username = " + username);
        return existsUser;
    }

    @Override
    public UserInfo selectById(Long id) {
        // 1. 非空校验
        if (id == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 2.查询数据库
        UserInfo user = userMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId, id));
        if (user == null || user.getDeleteState() == 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        // 1. 非空校验
        if (id == null || id <= 0) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 2. 根据id查找用户
        UserInfo user = userMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId, id).eq(UserInfo::getDeleteState,0));
        if (user == null || user.getDeleteState() == 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        UserInfo updateUser = new UserInfo();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        // 3. 更新数据
        userMapper.update(updateUser,new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId,id));
        log.info("更新成功");
    }

    @Override
    public void subOneArticleCountById(Long id) {
        // 1. 非空校验
        if (id == null || id <= 0) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 2. 根据id查找用户
        UserInfo user = userMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId, id).eq(UserInfo::getDeleteState,0));
        if (user == null || user.getDeleteState() == 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        UserInfo updateUser = new UserInfo();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        if (updateUser.getArticleCount() < 0) {
            // 如果小于0，则设置为0
            updateUser.setArticleCount(0);
        }
        // 3. 更新数据
        int row = userMapper.update(updateUser, new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId, id));
        if (row != 1) {
            checkFailUtils.checkFail(ResultCode.ERROR_SERVICES);
        }
        log.info("删除成功");
    }

    @Override
    public void modifyInfo(UserInfo user) {
        if (user == null || user.getId() == null || user.getId() <= 0) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 2. 校验用户是否存在
        UserInfo existsUser = userMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId,user.getId()));
        if (existsUser == null || existsUser.getDeleteState() == 1) {
          checkFailUtils.checkFail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 3. 定义一个标志位
        boolean checkAttr = false; // false表示没有校验通过

        // 4. 定义一个专门用来更新的对象，防止用户传入的User对象设置了其他的属性
        // 当使用动态SQL进行更新的时候，覆盖了没有经过校验的字段
        UserInfo updateUser = new UserInfo();
        // 5. 设置用户Id
        updateUser.setId(user.getId());

        // 6. 校验昵称
        if (!StringUtil.isNullOrEmpty(user.getNickname())
                && !user.getNickname().equals(existsUser.getNickname())) {
            // 设置昵称
            updateUser.setNickname(user.getNickname());
            // 更新标志位
            checkAttr = true;
        }
        // 7. 校验性别
        if (user.getGender() != null && user.getGender() != existsUser.getGender()) {
            // 设置性别
            updateUser.setGender(user.getGender());
            // 合法性校验
            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            // 更新标志位
            checkAttr = true;
        }
        // 8. 校验邮箱
        if (!StringUtil.isNullOrEmpty(user.getEmail())
                && !user.getEmail().equals(existsUser.getEmail())) {
            // 设置邮箱
            updateUser.setEmail(user.getEmail());
            // 更新标志位
            checkAttr = true;
        }
        // 9. 校验电话号码
        if (!StringUtil.isNullOrEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            // 设置电话号码
            updateUser.setPhoneNum(user.getPhoneNum());
            // 更新标志位
            checkAttr = true;
        }
        // 10. 校验个人简介
        if (!StringUtil.isNullOrEmpty(user.getRemark())
                && !user.getRemark().equals(existsUser.getRemark())) {
            // 设置电话号码
            updateUser.setRemark(user.getRemark());
            // 更新标志位
            checkAttr = true;
        }
        if (!StringUtil.isNullOrEmpty(user.getAvatarUrl())
                && !user.getAvatarUrl().equals(existsUser.getAvatarUrl())) {
            // 设置头像
            updateUser.setAvatarUrl(user.getAvatarUrl());
            // 更新标志位
            checkAttr = true;
        }
        if (!checkAttr) {
            checkFailUtils.checkFail("请输入修改内容");
        }
        userMapper.update(updateUser,new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId,updateUser.getId()));
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if (id == null || newPassword == null || oldPassword == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        UserInfo user = userMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId, id));
        String salt = user.getSalt();
        String ciphertext = MD5Utils.md5Salt(oldPassword,salt);
        // 判断密码是否正确
        if (!user.getPassword().equals(ciphertext)) {
            checkFailUtils.checkFail(ResultCode.FAILED_LOGIN);
        }
        salt = UUIDUtils.UUID_32();
        ciphertext = MD5Utils.md5Salt(newPassword,salt);
        UserInfo updateUser = new UserInfo();
        updateUser.setId(id);
        updateUser.setSalt(salt);
        updateUser.setPassword(ciphertext);
        userMapper.update(updateUser,new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId, id));
    }
}
